﻿@using WebSocketDemo.Manager;
@using System.Linq;
@{
    Layout = null;
    ViewData["Title"] = "WebSocket";
    var SendId = ViewBag.SendId as string;
    var ReceiveId = ViewBag.ReceiveId as string;
}

<style>

    html, body {
        height: 100%;
    }

    img {
        cursor: zoom-in;
    }

    input {
        vertical-align: super;
    }

    ul, h3 {
        display: inline-block;
        width: 50%;
    }

    h3 {
        padding-left: 40px;
    }

    ul {
        list-style: none;
    }

        ul li {
            position: relative;
            margin: 10px 0;
        }

            ul li.item {
                border: 1px solid #b0cef2;
                padding-right: 130px;
            }

    textarea {
        width: 500px;
        height: 250px;
    }

    .Receive {
        background: #e4e9f3;
    }

    .Send {
        background: #a0f3b6;
    }

    .ChatTime {
        position: absolute;
        right: 10px;
        top: 3px;
        font-size: 12px;
    }

    .ChatImgTime {
        position: absolute;
        right: 10px;
        top: 44px;
        font-size: 12px;
    }

    .container {
        display: flex;
        justify-content: center;
        align-items: center;
        position: fixed;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        background-color: #777;
        opacity: 0.98;
        z-index: 100;
    }
</style>

<body id="MainContent" onscroll="ScrollMainContent()">
    <div class="container" id="container" style="display: none;" onclick="ToggleBigImg()">
        <img src="" style="height:500px;width:auto;cursor:zoom-out;" id="bigImg" />
    </div>
    <a href="/Home/Websocket/1?to=2" target="_blank">用户1</a>
    <a href="/Home/Websocket/2?to=1" target="_blank">用户2</a>
    <input type="button" onclick="StartLink()" value="开始连接" hidden /><br />
    <textarea value="" id="msg"></textarea>
    <input type="button" onclick="SendMsg()" value="发送消息" />
    <input type="file" class="file" placeholder="上传聊天文件" accept="image/*" id="file" />
    <img id="img" src="" style="display:none;width:auto;height:100px;" />
    <input type="button" onclick="SendImg()" value="发送图片" />
    <div style="display:flex;">
        <h3>收到消息：</h3>
        <h3>发送消息：</h3>
    </div>
    <div style="display:flex;">
        <ul id="ReceiveContent"></ul>
        <ul id="SendContent"></ul>
    </div>
    <div style="min-height:50px;"></div>
</body>

<script src="https://cdn.bootcss.com/jquery/1.8.2/jquery.js"></script>
<script src="~/js/reconnecting-websocket.js"></script>
@*<script src="https://cdn.bootcss.com/reconnecting-websocket/1.0.0/reconnecting-websocket.js"></script>*@
<script>

    $(function () {
        $.post('/Home/GetMsgList', { id: '@SendId', to: '@ReceiveId' }, function (rs) {
            if (!!!rs) {
                return;
            }
            for (var i = 0; i < rs.totalMsg.length; i++) {
                var item = rs.totalMsg[i];
                if (item.messageType === 'Send') {//右边
                    if (item.content.indexOf('data:image') != -1) {//图片
                        document.getElementById('SendContent').innerHTML += '<li class=\"item\"> <img index=\"'+ i +'\" class=\"fakedImg\" onclick= \"ToggleImg(this)\" src=\"'
                            + '\" faked-src=\"' + item.content + '\" style=\"width:auto;height:100px;vertical-align:middle;\"><span class=\"ChatImgTime\">' + item.chatTime + '</span > </li>';
                        document.getElementById('ReceiveContent').innerHTML += '<li style=\"min-height: 100px;\"></li>';
                    } else {//文本
                        document.getElementById('SendContent').innerHTML += '<li class=\"item\"> <span class=\"Send\">' + item.content
                            + '</span><span class=\"ChatTime\">' + item.chatTime + '</span ></li> ';
                        document.getElementById('ReceiveContent').innerHTML += '<li style=\"min-height: 21px;\"></li>';
                    }
                } else if (item.messageType === 'Receive') {//左边
                    if (item.content.indexOf('data:image') != -1) {//图片
                        if (item.notReadMsg) {
                            alert('在' + item.chatTime+'收到未读图片');
                        }
                        document.getElementById('ReceiveContent').innerHTML += '<li class=\"item\"> <img index=\"' + i +'\" class=\"fakedImg\" onclick= \"ToggleImg(this)\" src=\"'
                            + '\" faked-src=\"' + item.content + '\" style=\"width:auto;height:100px;vertical-align:middle;\"><span class=\"ChatImgTime\">' + item.chatTime + '</span > </li>';
                        document.getElementById('SendContent').innerHTML += '<li style=\"min-height: 100px;\"></li>';
                    } else {//文本
                        if (item.notReadMsg) {
                            alert('在' + item.chatTime + '收到未读消息：' + item.content);
                        }
                        document.getElementById('ReceiveContent').innerHTML += '<li class=\"item\"> <span class=\"Receive\">' + item.content
                            + '</span><span class=\"ChatTime\">' + item.chatTime + '</span ></li> ';
                        document.getElementById('SendContent').innerHTML += '<li style=\"min-height: 21px;\"></li>';
                    }
                }
            }

            // 修改未读状态成已读
            $.post('/Home/UpdateReadMsgStatus', { ReceiverID : '@SendId', SenderID : '@ReceiveId' }, function (rs) {
                //alert('修改成功！');
            });

            // 页面加载时计算一次
            ScrollMainContent();
        });
    });

    var protocol = location.protocol === "https:" ? "wss:" : "ws:";
    var url = protocol + window.location.host + "/ws?sid="+'@SendId';
    var socket = null;

    //页面初始化开始连接
    window.onload = function () {
        StartLink();
    }

    //页面关闭断开连接
    window.onclose = function () {
        socket.close();
    }

    //开始连接WebScoket
    function StartLink() {
        socket = new ReconnectingWebSocket(url, null, { debug: true });
        socket.onopen = function () {
            console.log("连接成功!");
        }
        socket.onmessage = function (e) {
            console.log("收到消息：" + e.data);
            var rs = JSON.parse(e.data);
            if (rs) {
                if (rs.Content.indexOf('data:image') != -1) {//图片
                    document.getElementById('ReceiveContent').innerHTML += '<li onclick= \"ToggleImg(this)\" class=\"item\"> <img src=\"' + rs.Content
                        + '\" style=\"width:auto;height:100px;vertical-align:middle;\"><span class=\"ChatImgTime\">' + rs.ChatTime + '</span > </li>';
                    document.getElementById('SendContent').innerHTML += '<li style=\"min-height: 100px;\"></li>';
                } else {//文本
                    document.getElementById('ReceiveContent').innerHTML += '<li class=\"item\"> <span class=\"Receive\">' + rs.Content
                        + '</span><span class=\"ChatTime\">' + rs.ChatTime + '</span ></li> ';
                    document.getElementById('SendContent').innerHTML += '<li style=\"min-height: 21px;\"></li>';
                }
            }
        }
        socket.onerror = function () {
            console.log("连接错误!");
        }
        socket.onclose = function () {
            console.log("连接关闭!");
        }
    }

    //发送消息
    function SendMsg() {
        var msg = document.getElementById('msg').value;
        if (!!!msg.trim()) {
            alert('不能发送空消息');
            return;
        }
        var msgObj = {
            SenderID: "@SendId",
            ReceiverID: "@ReceiveId",
            MessageType: "Send",
            Content: msg
        };

        socket.send(JSON.stringify(msgObj));
        document.getElementById('SendContent').innerHTML += '<li class=\"item\"> <span class=\"Send\">' + msg + '</span><span class=\"ChatTime\">'
            + CurentTime() + '</span ></li> ';
        document.getElementById('ReceiveContent').innerHTML += '<li style=\"min-height: 21px;\"></li>';
        document.getElementById('msg').value = '';
    }

    //发送图片
    function SendImg() {
        var img = document.getElementById('img').src;
        if (location.href.indexOf(img) != -1) {
            alert('不能发送空图片');
            return;
        }
        var imgObj = {
            SenderID: "@SendId",
            ReceiverID: "@ReceiveId",
            MessageType: "Send",
            Content: img
        };

        socket.send(JSON.stringify(imgObj));
        document.getElementById('SendContent').innerHTML += '<li class=\"item\"> <img onclick= \"ToggleImg(this)\" src=\"' + img + '\" style=\"width:auto;height:100px;vertical-align:middle;\"><span class=\"ChatImgTime\">'
            + CurentTime() + '</span > </li>';
        document.getElementById('ReceiveContent').innerHTML += '<li style=\"min-height: 100px;\"></li>';
        document.getElementById('img').src = '';
        $('#img').hide();
    }

    //上传图片的onchange事件
    $("#file").on("change", function () {
        //var path = $(this).val();
        var reader = new FileReader();
        var obj = this.files[0];

        if (obj.type.indexOf('image') != -1) {
            // 将图片读成dataURL
            reader.readAsDataURL(obj);
            reader.onload = function () {
                $('#img').attr('src', this.result);
                $('#img').show();
            }
        } else {
            alert('您未上传文件，或者您上传文件类型有误！');
        }
    });

    //获取当前时间
    function CurentTime() {
        var now = new Date();

        var year = now.getFullYear();       //年
        var month = now.getMonth() + 1;     //月
        var day = now.getDate();            //日

        var hh = now.getHours();            //时
        var mm = now.getMinutes();          //分
        var ss = now.getSeconds();          //秒

        var clock = year + "-";

        if (month < 10) {
            clock += "0";
        }
        clock += month + "-";

        if (day < 10) {
            clock += "0";
        }
        clock += day + " ";

        if (hh < 10) {
            clock += "0";
        }
        clock += hh + ":";

        if (mm < 10) {
            clock += '0';
        }
        clock += mm + ":";

        if (ss < 10) {
            clock += '0';
        }
        clock += ss;

        return (clock);
    }

    //图片点击事件
    function ToggleImg(id) {
        var src = $(id).attr('src');
        $('#bigImg').attr('src', src);
        $('#container').show();
    }

    //大图点击事件
    function ToggleBigImg() {
        $('#container').hide();
    }

    //存储图片加载到的位置，避免每次都从第一张图片开始遍历
    var n = 0;
    //用户懒加载的图片对象 不寻找img是因为img的offsetParent是li
    aImg = document.getElementsByClassName('item');

    //图片懒加载
    var ScrollMainContent = function () {
        var seeHeight = $("#MainContent").height();
        var scrollTop = $("#MainContent").scrollTop();

        for (var i = 0; i < aImg.length; i++) {
            if (aImg[i].offsetTop < seeHeight + scrollTop) {
                if (aImg[i].getElementsByClassName('fakedImg').length === 0) {
                    continue;
                }
                if (aImg[i].getElementsByClassName('fakedImg')[0].getAttribute('src') == '') {

                    aImg[i].getElementsByClassName('fakedImg')[0].src = aImg[i].getElementsByClassName('fakedImg')[0].getAttribute('faked-src');
                }
                n = i + 1;
            }
        }
    };
</script>
